package com.xiaohudie.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

@Configuration
public class UserAndPasswordTest extends WebSecurityConfigurerAdapter {
    @Resource
    private UserDetailsService userDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**返回没有权限的页面，跳转页面*/
        http.exceptionHandling().accessDeniedPage("/uncan.html");
       /**登录界面设置
        * 登录访问地址
        * 登录成功之后访问的地址*/
       http.formLogin().loginPage("/login.html").loginProcessingUrl("/user/login").defaultSuccessUrl("/test/index").permitAll()
               .and().authorizeRequests()
               /**设置哪些方法不需要权限即可访问*/
               .antMatchers("/","/test/hello","/user/login").permitAll()
               /**设置只有有了这个权限才能访问*/
              // .antMatchers("/test/index").hasAuthority("admins")
               /**当你有两个权限之后需要使用hasAnyAuthority*/
              //.antMatchers("/test/index").hasAnyAuthority("admins,role")
               /**当你有了这个角色之后才能访问的情况*/
               .antMatchers("test/index").hasRole("sale")
               /**设置所有都可以访问的方法*/
               .anyRequest().authenticated()
               /**关闭csrf防护装置*/
               .and().csrf().disable();

    }
}
